package com.bw.ogin.vm

import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.GsonUtils
import com.bw.common.vm.BaseViewModel
import com.bw.ogin.intent.LoginViewIntent
import com.bw.ogin.model.LoginRepository
import com.bw.ogin.model.LoginRepositoryHilt
import com.bw.ogin.state.LoginUiState
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody.Companion.toResponseBody
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(private val respository:LoginRepositoryHilt) :BaseViewModel<LoginViewIntent>() {

    private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.NoneState) //当前类中使用，可以修改流中的数据
    val uiState:StateFlow<LoginUiState> = _uiState.asStateFlow()//外部只用于接收流的数据不能修改


    override fun dispatchIntent(intent: LoginViewIntent) {
        when(intent){
            is LoginViewIntent.LoginToServer->
                loginToServer(intent.name,intent.pwd)
            is LoginViewIntent.RegisterToServer->
               RegisterToServer(intent.name,intent.pwd)
            else->{}
        }
    }

    private fun RegisterToServer(name: String, pwd: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //封装参数
                var mapParams = mutableMapOf("uName" to name, "uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis() / 1000).toString()
                var jsonParams = GsonUtils.toJson(mapParams)
                var paramsBody =
                    jsonParams.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

                //调用仓库中的挂起方法
                var resultData = respository.registerToServer(paramsBody)
                if (resultData.statusCode == "200") {
                    MMKV.defaultMMKV().encode("token", resultData.getValues().token)
                    MMKV.defaultMMKV().encode("home_url", resultData.home)
                    MMKV.defaultMMKV().encode("userId", resultData.getValues().uld)

                    _uiState.value = LoginUiState.RegisterSuccess(resultData.getValues())
                } else {
                    _uiState.value = LoginUiState.RegisterFail(resultData.msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.value = LoginUiState.RegisterFail(e.message ?: "接口异常，请联系客服")

            } finally {
                //取消携程
                cancel()
            }
        }
    }

    private fun loginToServer(name: String, pwd: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //封装参数
                var mapParams = mutableMapOf("uName" to name,"uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis() / 1000).toString()
                var jsonParams = GsonUtils.toJson(mapParams)
                var paramsBody = jsonParams.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

                //调用仓库中的挂起方法
                var resultData = respository.loginToServer(paramsBody)
                if(resultData.statusCode == "200"){
                    MMKV.defaultMMKV().encode("token",resultData.getValues().token)
                    MMKV.defaultMMKV().encode("home_url",resultData.home)
                    MMKV.defaultMMKV().encode("userId",resultData.getValues().uld)

                    _uiState.value = LoginUiState.LoginSuccess(resultData.getValues())
                }else{
                    _uiState.value = LoginUiState.LoginFail(resultData.msg)
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.value = LoginUiState.LoginFail(e.message?:"接口异常，请联系客服")

            }finally {
                //取消携程
                cancel()
            }
        }
    }

}